package org.example.school.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 30分钟过期时间（毫秒）
    private static final long EXPIRE_TIME = 30 * 60 * 1000;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");

    /**
     * 生成Redis键名：学号 + 日期
     * @param studentNumber 学号
     * @return Redis键名
     */
    public String generateKey(String studentNumber, LocalDate date) {
        String datePart = date.format(DATE_FORMATTER);
        return "leave:" + studentNumber + ":" + datePart;
    }

    /**
     * 保存请假码到Redis
     * @param studentNumber 学号
     * @param leaveCode 请假码
     */
    public void saveLeaveCode(String studentNumber, String leaveCode, LocalDate  date) {
        String key = generateKey(studentNumber,date);
        redisTemplate.opsForValue().set(key, leaveCode, EXPIRE_TIME);
    }

    /**
     * 根据学号获取请假码
     * @param studentNumber 学号
     * @return 请假码
     */
    public String getLeaveCode(String studentNumber, LocalDate date) {
        String key = generateKey(studentNumber, date);
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除请假码
     * @param studentNumber 学号
     */
    public void deleteLeaveCode(String studentNumber, LocalDate date) {
        String key = generateKey(studentNumber,date);
        if(!redisTemplate.hasKey(key)){
            return;
        }
        redisTemplate.delete(key);
    }
}
